﻿using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Text;

class MyWWW
{
    public byte[] result { get; private set; }
    public string url { get; private set; }
    public byte[] data { get; private set; }

    public string text
    {
        get { return Encoding.UTF8.GetString(result); }
    }

    public MyWWW()
    {
        url = "";
        result = null;
        data = null;
    }

    public MyWWW(string url)
    {
        this.url = url;
        result = Get(url);
    }

    public MyWWW(string url, byte[] data)
    {
        this.url = url;
        this.data = data;
        result = Post(url, data);            
    }

    public byte[] Get(string url)
    {
        this.url = url;
        List<byte> result = new List<byte>();
        HttpWebRequest rq = (HttpWebRequest)HttpWebRequest.Create(url);

        using (HttpWebResponse rs = (HttpWebResponse)rq.GetResponse())
        {
            using(Stream stream = rs.GetResponseStream())
            {
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int length = stream.Read(buffer, 0, buffer.Length);
                    for(int i = 0; i < length; i++)
                    {
                        result.Add(buffer[i]);
                    }

                    if (length == 0)
                        break;
                }
            }
        }

        this.result = result.ToArray();
        return this.result;
    }

    public byte[] Post(string url,byte[] data)
    {
        List<byte> result = new List<byte>();

        HttpWebRequest rq = (HttpWebRequest)HttpWebRequest.Create(url);
        rq.Method = "POST";
        rq.ContentLength = data.Length;

        using (Stream stream = rq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        using (HttpWebResponse rs = (HttpWebResponse)rq.GetResponse())
        {
            using (Stream stream = rs.GetResponseStream())
            {
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int length = stream.Read(buffer, 0, buffer.Length);
                    for (int i = 0; i < length; i++)
                    {
                        result.Add(buffer[i]);
                    }

                    if (length == 0)
                        break;
                }
            }

        }


        this.result = result.ToArray();
        return this.result;
    }

}
